document.addEventListener('DOMContentLoaded', function() {
  // DOM elements
  const extractBtn = document.getElementById('extract-btn');
  const chatMessages = document.getElementById('chat-messages');
  const chatInput = document.getElementById('chat-input');
  const sendMessageBtn = document.getElementById('send-message-btn');
  const statusMessage = document.getElementById('status-message');
  const aiProviderSelect = document.getElementById('ai-provider');
  const ollamaSettings = document.getElementById('ollama-settings');
  const openaiSettings = document.getElementById('openai-settings');
  const saveSettingsBtn = document.getElementById('save-settings');
  const customPromptTextarea = document.getElementById('custom-prompt');
  const settingsBtn = document.getElementById('settings-btn');
  const settingsPanel = document.querySelector('.settings-panel');
  const closeBtn = document.getElementById('close-btn');
  const minimizeBtn = document.getElementById('minimize-btn');
  const expandBtn = document.getElementById('expand-btn');
  const videoTitle = document.getElementById('video-title');
  const videoChannel = document.getElementById('video-channel');
  
  // Load saved settings
  loadSettings();
  
  // Add extension ID info to Ollama settings
  addExtensionIdInfo();
  
  // Event listeners
  extractBtn.addEventListener('click', extractSubtitles);
  saveSettingsBtn.addEventListener('click', saveSettings);
  aiProviderSelect.addEventListener('change', toggleAISettings);
  sendMessageBtn.addEventListener('click', sendMessage);
  
  // Handle Shift+Enter to send message
  chatInput.addEventListener('keydown', function(e) {
    if (e.key === 'Enter' && e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  });
  
  // Settings button
  if (settingsBtn) {
    settingsBtn.addEventListener('click', function() {
      settingsPanel.style.display = 'block';
    });
  }
  
  // Close button
  if (closeBtn) {
    closeBtn.addEventListener('click', function() {
      window.close();
    });
  }
  
  // Minimize button
  if (minimizeBtn) {
    minimizeBtn.addEventListener('click', function() {
      // Implement minimize functionality if needed
    });
  }
  
  // Expand button
  if (expandBtn) {
    expandBtn.addEventListener('click', function() {
      // Implement expand functionality if needed
    });
  }
  
  // Sidebar buttons
  const sidebarBtns = document.querySelectorAll('.sidebar-btn');
  sidebarBtns.forEach(btn => {
    btn.addEventListener('click', function() {
      // Remove active class from all buttons
      sidebarBtns.forEach(b => b.classList.remove('active'));
      // Add active class to clicked button
      this.classList.add('active');
      
      // Handle specific sidebar button actions
      if (this.id === 'settings-btn') {
        settingsPanel.style.display = 'block';
      } else if (settingsPanel) {
        settingsPanel.style.display = 'none';
      }
    });
  });
  
  // Add extension ID info to Ollama settings
  function addExtensionIdInfo() {
    const extensionId = chrome.runtime.id;
    const infoDiv = document.createElement('div');
    infoDiv.className = 'ollama-cors-info';
    infoDiv.innerHTML = `
      <p class="info-text">To avoid CORS errors, run Ollama with:</p>
      <code>OLLAMA_ORIGINS=chrome-extension://${extensionId} ollama serve</code>
      <p class="info-text">Your extension ID: <strong>${extensionId}</strong></p>
    `;
    ollamaSettings.appendChild(infoDiv);
  }
  
  // Toggle AI provider settings
  function toggleAISettings() {
    if (aiProviderSelect.value === 'ollama') {
      ollamaSettings.style.display = 'flex';
      openaiSettings.style.display = 'none';
    } else {
      ollamaSettings.style.display = 'none';
      openaiSettings.style.display = 'flex';
    }
  }
  
  // Extract subtitles from the current YouTube video
  function extractSubtitles() {
    showStatus('Extracting video subtitles...', 'info');
    extractBtn.disabled = true;
    
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      const activeTab = tabs[0];
      
      // Check if we're on a YouTube video page
      if (!activeTab.url.includes('youtube.com/watch')) {
        showStatus('Please navigate to a YouTube video page', 'error');
        extractBtn.disabled = false;
        return;
      }
      
      // Get video title and channel
      chrome.tabs.sendMessage(activeTab.id, {action: 'getVideoInfo'}, function(videoInfo) {
        if (videoInfo && videoInfo.title) {
          videoTitle.textContent = videoInfo.title;
          videoChannel.textContent = videoInfo.channel || '';
        }
      });
      
      console.log('Sending extractSubtitles message to content script');
      
      chrome.tabs.sendMessage(activeTab.id, {action: 'extractSubtitles'}, function(response) {
        extractBtn.disabled = false;
        
        if (chrome.runtime.lastError) {
          console.error('Runtime error:', chrome.runtime.lastError);
          
          // Check if content script is not loaded
          if (chrome.runtime.lastError.message.includes('receiving end does not exist')) {
            showStatus('Extension not initialized. Please refresh the page and try again.', 'error');
            return;
          }
          
          showStatus('Error: ' + chrome.runtime.lastError.message, 'error');
          return;
        }
        
        if (response && response.success) {
          // Add the subtitles to the chat input
          chatInput.value = customPromptTextarea.value.replace('{transcript}', response.subtitles);
          chatInput.focus();
          sendMessageBtn.disabled = false;
          
          // Add system message to chat
          addSystemMessage('字幕提取成功！您可以发送消息来总结它们。');
          
          showStatus('字幕提取成功！', 'success');
        } else {
          const errorMsg = response ? response.error : 'Unknown error';
          console.error('Failed to extract subtitles:', errorMsg);
          showStatus('提取字幕失败: ' + errorMsg, 'error');
        }
      });
    });
  }
  
  // Send a message from the chat input
  function sendMessage() {
    if (chatInput.value.trim() === '') {
      return;
    }
    
    summarizeSubtitles();
  }
  
  // Summarize the extracted subtitles
  function summarizeSubtitles() {
    const settings = getAISettings();
    
    // Validate settings
    const validationError = validateSettings(settings);
    if (validationError) {
      showStatus(validationError, 'error');
      return;
    }
    
    // Get the current message from the chat input
    const message = chatInput.value.trim();
    if (!message) {
      showStatus('请输入要发送的消息', 'error');
      return;
    }
    
    // Add user message to chat
    addUserMessage(message);
    
    // Clear input
    chatInput.value = '';
    
    // Disable buttons during summarization
    sendMessageBtn.disabled = true;
    
    showStatus('正在生成摘要...', 'info');
    
    // Generate a unique message ID for streaming
    const messageId = Date.now().toString();
    
    // Create a placeholder for the AI response
    const aiMessageElement = addAIMessage('', messageId);
    
    // Set up listener for streaming updates
    const streamListener = function(message, sender, sendResponse) {
      if (message.action === 'streamUpdate' && message.messageId === messageId) {
        if (message.error) {
          aiMessageElement.textContent = 'Error: ' + message.error;
          aiMessageElement.classList.add('error');
          showStatus('生成摘要时出错: ' + message.error, 'error');
          sendMessageBtn.disabled = false;
          chrome.runtime.onMessage.removeListener(streamListener);
          return;
        }
        
        // Update the AI message with the new chunk
        aiMessageElement.innerHTML = renderMarkdown(message.text);
        
        // If this is the final chunk, clean up
        if (message.done) {
          showStatus('摘要生成成功！', 'success');
          sendMessageBtn.disabled = false;
          chrome.runtime.onMessage.removeListener(streamListener);
        }
      }
    };
    
    chrome.runtime.onMessage.addListener(streamListener);
    
    // Send the summarization request
    chrome.runtime.sendMessage({
      action: 'summarizeStream',
      subtitles: message,
      settings: settings,
      messageId: messageId
    });
  }
  
  // Add a user message to the chat
  function addUserMessage(text) {
    const messageElement = document.createElement('div');
    messageElement.className = 'chat-message user-message';
    messageElement.textContent = text;
    chatMessages.appendChild(messageElement);
    chatMessages.scrollTop = chatMessages.scrollHeight;
    return messageElement;
  }
  
  // Add an AI message to the chat
  function addAIMessage(text, messageId) {
    const messageElement = document.createElement('div');
    messageElement.className = 'chat-message ai-message';
    messageElement.dataset.messageId = messageId;
    messageElement.innerHTML = text ? renderMarkdown(text) : '';
    chatMessages.appendChild(messageElement);
    chatMessages.scrollTop = chatMessages.scrollHeight;
    return messageElement;
  }
  
  // Add a system message to the chat
  function addSystemMessage(text) {
    const messageElement = document.createElement('div');
    messageElement.className = 'chat-message system-message';
    messageElement.textContent = text;
    chatMessages.appendChild(messageElement);
    chatMessages.scrollTop = chatMessages.scrollHeight;
    return messageElement;
  }
  
  // Render markdown to HTML
  function renderMarkdown(text) {
    // Simple markdown rendering
    // This is a basic implementation - you might want to use a library like marked.js for more complete markdown support
    
    // Convert headers
    text = text.replace(/^### (.*$)/gm, '<h3>$1</h3>');
    text = text.replace(/^## (.*$)/gm, '<h2>$1</h2>');
    text = text.replace(/^# (.*$)/gm, '<h1>$1</h1>');
    
    // Convert bold and italic
    text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
    text = text.replace(/\*(.*?)\*/g, '<em>$1</em>');
    
    // Convert lists
    text = text.replace(/^\s*\*\s(.*$)/gm, '<li>$1</li>');
    text = text.replace(/(<li>.*<\/li>)/s, '<ul>$1</ul>');
    
    // Convert code blocks
    text = text.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>');
    
    // Convert inline code
    text = text.replace(/`([^`]+)`/g, '<code>$1</code>');
    
    // Convert paragraphs
    text = text.replace(/^(?!<[a-z])/gm, '<p>');
    text = text.replace(/^(?!<\/[a-z])/gm, '</p>');
    
    // Wrap in a div with markdown-content class
    return '<div class="markdown-content">' + text + '</div>';
  }
  
  // Validate AI settings
  function validateSettings(settings) {
    if (settings.provider === 'ollama') {
      if (!settings.ollamaUrl) {
        return 'Ollama URL is required';
      }
      if (!settings.ollamaModel) {
        return 'Ollama model is required';
      }
    } else if (settings.provider === 'openai') {
      if (!settings.openaiUrl) {
        return 'OpenAI API URL is required';
      }
      if (!settings.openaiKey) {
        return 'OpenAI API key is required';
      }
      if (!settings.openaiModel) {
        return 'OpenAI model is required';
      }
    } else {
      return 'Invalid AI provider';
    }
    
    return null;
  }
  
  // Get AI settings from form
  function getAISettings() {
    const provider = aiProviderSelect.value;
    
    const settings = {
      provider: provider,
      customPrompt: customPromptTextarea.value
    };
    
    if (provider === 'ollama') {
      settings.ollamaUrl = document.getElementById('ollama-url').value;
      settings.ollamaModel = document.getElementById('ollama-model').value;
    } else if (provider === 'openai') {
      settings.openaiUrl = document.getElementById('openai-url').value;
      settings.openaiKey = document.getElementById('openai-key').value;
      settings.openaiModel = document.getElementById('openai-model').value;
    }
    
    return settings;
  }
  
  // Save settings to storage
  function saveSettings() {
    const settings = getAISettings();
    chrome.storage.sync.set({ aiSettings: settings }, function() {
      showStatus('设置保存成功！', 'success');
      
      // Hide settings panel after saving
      if (settingsPanel) {
        settingsPanel.style.display = 'none';
      }
      
      // Activate chat button
      const chatBtn = document.getElementById('chat-btn');
      if (chatBtn) {
        sidebarBtns.forEach(b => b.classList.remove('active'));
        chatBtn.classList.add('active');
      }
    });
  }
  
  // Load settings from storage
  function loadSettings() {
    chrome.storage.sync.get('aiSettings', function(data) {
      if (data.aiSettings) {
        const settings = data.aiSettings;
        
        // Set AI provider
        aiProviderSelect.value = settings.provider;
        toggleAISettings();
        
        // Set custom prompt
        if (settings.customPrompt) {
          customPromptTextarea.value = settings.customPrompt;
        }
        
        // Set Ollama settings
        if (settings.ollamaUrl) {
          document.getElementById('ollama-url').value = settings.ollamaUrl;
        }
        if (settings.ollamaModel) {
          document.getElementById('ollama-model').value = settings.ollamaModel;
        }
        
        // Set OpenAI settings
        if (settings.openaiUrl) {
          document.getElementById('openai-url').value = settings.openaiUrl;
        }
        if (settings.openaiKey) {
          document.getElementById('openai-key').value = settings.openaiKey;
        }
        if (settings.openaiModel) {
          document.getElementById('openai-model').value = settings.openaiModel;
        }
      }
    });
  }
  
  // Show status message
  function showStatus(message, type) {
    statusMessage.textContent = message;
    statusMessage.className = 'status-message';
    statusMessage.classList.add(type);
    
    // Clear status after 5 seconds
    setTimeout(() => {
      statusMessage.textContent = '';
      statusMessage.className = 'status-message';
    }, 5000);
  }
}); 